import {useState} from 'react';
import {useNavigate} from "react-router-dom";

// 登录

interface LoginResponse {
    code: number;
    identity: string;
    token: string;
    message: string;
}

interface UseLogin {
    login: (id: string, password: string) => Promise<void>;
    isLoading: boolean;
    error: string | null;
}

export function useLogin(): UseLogin {
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const navigate = useNavigate();

    const login = async (id: string, password: string): Promise<void> => {
        setIsLoading(true);
        setError(null);
        try {
            const response = await fetch('http://localhost:6868/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({id, password}),
            });

            if (!response.ok) {
                throw new Error('登录失败');
            }

            const data: LoginResponse = await response.json();
            localStorage.setItem('token', data.token);
            localStorage.setItem('identity', data.identity);
            if (data.identity == 'employee') {
                navigate('/userMainWindow');
            } else if (data.identity == 'admin') {
                navigate('/adminMainWindow');
            } else {
                navigate('/superAdminMainWindow');
            }
        } catch (error) {
            setError((error as Error).message);
        } finally {
            setIsLoading(false);
        }
    };

    return {login, isLoading, error};
}
